package com.gengzp.mq.server.runner;

import com.gengzp.mq.server.enums.MqMessageStatusEnums;
import com.gengzp.mq.server.facade.MqMessageFacadeService;
import com.gengzp.mq.server.manager.MqAckMessageManager;
import com.gengzp.mq.server.manager.MqObsoleteMessageManager;
import com.gengzp.mq.server.manager.MqResendMessageManager;
import com.gengzp.mq.server.model.message.entity.MqMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName MqCommandLineRunner
 * @Description 消息队列项目启动后自动执行任务
 * @Author gengzp
 * @Date 2025/9/4 15:22
 */
@Component
public class MqCommandLineRunner implements CommandLineRunner {

    @Autowired
    private MqResendMessageManager mqResendMessageManager;

    @Autowired
    private MqAckMessageManager mqAckMessageManager;

    @Autowired
    private MqObsoleteMessageManager mqObsoleteMessageManager;

    @Autowired
    private MqMessageFacadeService mqMessageFacadeService;

    @Override
    public void run(String... args) {
        // 1.开启消息重发任务
        mqResendMessageManager.createResendMessageJob();
        // 2.开启消息ack超时检测任务
        mqAckMessageManager.createMessageAckTimeoutInspectJob();
        // 3.开启过时消息检测任务
        mqObsoleteMessageManager.createObsoleteMessageJob();
        // 4.初始处理消息
        initialProcessMessages();
    }

    /**
     * 初始处理消息
     */
    private void initialProcessMessages() {
        // 处理超时未确认的消息
        processAckTimeoutMessages();
    }

    /**
     * 处理超时未确认消息
     */
    private void processAckTimeoutMessages() {
        // 查询所有消费中消息
        List<MqMessage> mqMessages = mqMessageFacadeService.
                searchMqMessagesByStatus(MqMessageStatusEnums.CONSUMING.getCode());
        if (mqMessages == null || mqMessages.isEmpty()) {
            return;
        }

        // 将消费中消息全部加入到Ack超时检查任务队列中
        mqAckMessageManager.sendMessageToAckTimeoutInspectJobQueue(mqMessages);
    }

}
